import datetime
import json
from functools import lru_cache

import pandas as pd
import requests


# 计算前一个工作日
def __get_trade_date__() -> str:
    trade_date = (datetime.date.today() - datetime.timedelta(days=1))
    # 如果前一个工作日是周末，则取上一个周五
    if trade_date.weekday() == 5:
        trade_date = (datetime.date.today() - datetime.timedelta(days=2)).strftime('%Y-%m-%d')
    elif trade_date.weekday() == 6:
        trade_date = (datetime.date.today() - datetime.timedelta(days=3)).strftime('%Y-%m-%d')
    else:
        trade_date = trade_date.strftime('%Y-%m-%d')
    return trade_date


__TRADE_DATE__: str = __get_trade_date__()  # 前一个交易日
__COLUMNS__: dict = {'SECURITY_CODE': '证券代码',
                     'SECUCODE': '证券代码2',
                     'SECURITY_NAME_ABBR': '证券简称',
                     'ORG_CODE': '机构代码',
                     'TRADE_MARKET': '交易市场',
                     'BOARD_CODE': '板块代码',
                     'BOARD_NAME': '板块名称',
                     'ORIG_BOARD_CODE': '原板块代码',
                     'TOTAL_MARKET_CAP': '总市值',
                     'NOTLIMITED_MARKETCAP_A': '流通市值A',
                     'CLOSE_PRICE': '收盘价',
                     'CHANGE_RATE': '换手率',
                     'TOTAL_SHARES': '总股本',
                     'FREE_SHARES_A': '流通A股',
                     'PE_TTM': 'PE(TTM)',
                     'PE_LAR': 'PE(LAR)',
                     'PB_MRQ': 'PB(MRQ)',
                     'PCF_OCF_LAR': 'PCF/OCF(LAR)',
                     'PCF_OCF_TTM': 'PCF/OCF(TTM)',
                     'PS_TTM': 'PS(TTM)',
                     'PEG_CAR': 'PEG(CAR)',
                     'TRADE_DATE': '交易日期',
                     'MARKET_CAP_VAG': '平均市值',
                     'NOMARKETCAP_A_VAG': '平均流通市值',
                     'TOTAL_SHARES_VAG': '平均股本（股）',
                     'FREE_SHARES_VAG': '平均流通股本（股）',
                     'NUM': '个股数量',
                     'LOSS_COUNT': '亏损家数',
                     'ORIGINALCODE': '原始代码',
                     }


@lru_cache(maxsize=128)
def stock_ev_em(code: str, pagesize: int = 5000, is_board: bool = False) -> pd.DataFrame | None:
    """
    获取股票的估值数据

    :param code: 股票代码
    :param pagesize: 每页大小
    :param is_board: 是否为板块
    :return: DataFrame
    """
    cookies = {'qgqp_b_id': '3f85baad4db59b09a7a018d3292ecfdd',
               'HAList': 'ty-1-688613-%u5965%u7CBE%u533B%u7597%2Cty-1-603777-%u6765%u4F0A%u4EFD',
               'st_si': '91329712287705',
               'st_asi': 'delete',
               'st_pvi': '42278406842012',
               'st_sp': '2022-03-07%2017%3A30%3A20',
               'st_inirUrl': 'https%3A%2F%2Fcn.bing.com%2F',
               'st_sn': '9',
               'st_psi': '20230814192228759-113300303064-7435672148',
               'JSESSIONID': '5E10F58C2C955F8DF0063DD693D096A0', }
    headers = {'Accept': '*/*',
               'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,pt;q=0.5',
               'Connection': 'keep-alive',
               'Referer': f'https://data.eastmoney.com/gzfx/detail/{code}.html',
               'Sec-Fetch-Dest': 'script',
               'Sec-Fetch-Mode': 'no-cors',
               'Sec-Fetch-Site': 'same-site',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'
                             '115.0.0.0 Safari/537.36 Edg/115.0.1901.203',
               'sec-ch-ua': '"Not/A)Brand";v="99", "Microsoft Edge";v="115", "Chromium";v="115"',
               'sec-ch-ua-mobile': '?0',
               'sec-ch-ua-platform': '"Windows"', }
    params = {'callback': 'jQuery1123012865361672893094_1692012148113',
              'sortColumns': 'TRADE_DATE',
              'sortTypes': '-1',
              'pageSize': f'{pagesize}',
              'pageNumber': '1',
              'reportName': 'RPT_VALUEANALYSIS_DET',
              'columns': 'ALL',
              'quoteColumns': '',
              'source': 'WEB',
              'client': 'WEB',
              'filter': f'(SECURITY_CODE="{code}")' if not is_board else f'(BOARD_CODE="{code}")', }
    response = requests.get('https://datacenter-web.eastmoney.com/api/data/v1/get',
                            cookies=cookies, headers=headers, params=params, )

    json_text = response.text
    json_text = json_text[json_text.find('(') + 1:-2]
    json_text = json.loads(json_text)
    try:
        json_text.get('result').get('data')
        dsn_ = pd.DataFrame.from_dict(json_text.get('result').get('data'))
        dsn_.rename(columns=__COLUMNS__, inplace=True)
        return dsn_
    except AttributeError:
        return None


@lru_cache(maxsize=128)
def board_ev_em(code: str, pagesize: int = 5000) -> pd.DataFrame | None:
    cookies = {
        'qgqp_b_id': '4f52fb4a713628167c04978dc7cb6675',
        'fullscreengg': '1',
        'fullscreengg2': '1',
        'st_si': '05972785628592',
        'st_asi': 'delete',
        'websitepoptg_api_time': '1750313633580',
        'st_pvi': '63006240941089',
        'st_sp': '2025-06-18%2016%3A11%3A31',
        'st_inirUrl': 'https%3A%2F%2Fdata.eastmoney.com%2Fgzfx%2Fdetail%2F000001.html',
        'st_sn': '8',
        'st_psi': '20250619141432956-113300303065-4127382341',
        'JSESSIONID': '55B44B2DD20B567B9BEF4231C13D5F83',
    }
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,pt;q=0.5',
        'Connection': 'keep-alive',
        'Referer': 'https://data.eastmoney.com/gzfx/hy/016028.html',
        'Sec-Fetch-Dest': 'script',
        'Sec-Fetch-Mode': 'no-cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/'
                      '605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/137.0.0.0',
    }
    params = {'callback': 'jQuery112308331232855639841_1750313672769',
              'sortColumns': 'TRADE_DATE',
              'sortTypes': '-1',
              'pageSize': f'{pagesize}',
              'pageNumber': '1',
              'reportName': 'RPT_VALUEINDUSTRY_DET',
              'columns': 'ALL',
              'quoteColumns': '',
              'source': 'WEB',
              'client': 'WEB',
              'filter': f'(BOARD_CODE="{code}")', }
    response = requests.get('https://datacenter-web.eastmoney.com/api/data/v1/get',
                            cookies=cookies, headers=headers, params=params, )

    json_text = response.text
    json_text = json_text[json_text.find('(') + 1:-2]
    json_text = json.loads(json_text)
    try:
        json_text.get('result').get('data')
        dsn_ = pd.DataFrame.from_dict(json_text.get('result').get('data'))
        dsn_.rename(columns=__COLUMNS__, inplace=True)
        return dsn_
    except AttributeError:
        return None


@lru_cache(maxsize=128)
def board_em() -> pd.DataFrame | None:
    cookies = {
        'qgqp_b_id': '4f52fb4a713628167c04978dc7cb6675',
        'fullscreengg': '1',
        'fullscreengg2': '1',
        'st_si': '05972785628592',
        'st_asi': 'delete',
        'websitepoptg_api_time': '1750313633580',
        'st_pvi': '63006240941089',
        'st_sp': '2025-06-18%2016%3A11%3A31',
        'st_inirUrl': 'https%3A%2F%2Fdata.eastmoney.com%2Fgzfx%2Fdetail%2F000001.html',
        'st_sn': '15',
        'st_psi': '20250619141432956-113300303065-4127382341',
        'JSESSIONID': '55B44B2DD20B567B9BEF4231C13D5F83',
    }
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,pt;q=0.5',
        'Connection': 'keep-alive',
        'Referer': 'https://data.eastmoney.com/gzfx/hy/016028.html',
        'Sec-Fetch-Dest': 'script',
        'Sec-Fetch-Mode': 'no-cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/'
                      '605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/137.0.0.0',
    }
    params = {'callback': 'jQuery112308331232855639841_1750313672769',
              'sortColumns': 'MARKET_CAP_VAG',
              'sortTypes': '-1',
              'pageSize': '1000',
              'pageNumber': '1',
              'reportName': 'RPT_VALUEINDUSTRY_DET',
              'columns': 'ALL',
              'quoteColumns': '',
              'source': 'WEB',
              'client': 'WEB',
              'filter': f'(TRADE_DATE=\'{__TRADE_DATE__}\')', }
    response = requests.get('https://datacenter-web.eastmoney.com/api/data/v1/get',
                            cookies=cookies, headers=headers, params=params, )

    json_text = response.text
    json_text = json_text[json_text.find('(') + 1:-2]
    json_text = json.loads(json_text)
    try:
        json_text.get('result').get('data')
        dsn_ = pd.DataFrame.from_dict(json_text.get('result').get('data'))
        dsn_.rename(columns=__COLUMNS__, inplace=True)
        return dsn_
    except AttributeError:
        return None


if __name__ == '__main__':
    data_ev = stock_ev_em('430047')  # 深市主板
    data_board_ev = board_ev_em('016028')  # 深市主板
    data_board = board_em()
